<template>
  <Dialog v-model="dialogVisible" title="配置管控单位" width="600">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="130px"
    >
      <el-form-item label="身份证号码" prop="idcard">
        <el-input v-model="formData.idcard" class="!w-240px" disabled/>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" class="!w-240px" disabled/>
      </el-form-item>
      <el-form-item label="分类名称" prop="groupName">
        <el-input v-model="formData.groupName" class="!w-240px" disabled/>
      </el-form-item>
      <el-form-item label="管控单位" prop="deptId">
        <el-tree-select class="!w-240px"
                        v-model="formData.deptIds"
                        :data="deptList"
                        :props="defaultProps"
                        :multiple="true"
                        :check-strictly="true"
                        :show-checkbox="true"
                        node-key="id"
                        placeholder="请选择管控单位"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as UserApi from '@/api/member/user';
import {defaultProps, handleTree} from '@/utils/tree';
import * as DeptApi from '@/api/system/dept'
import {DeptVO} from "@/api/system/dept";

/** 修改用户余额表单 */
defineOptions({name: 'DivideMember2DepartForm'});

const {t} = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗
const deptList = ref<Tree[]>([]) // 树形结构
const depts = ref<DeptVO[]>([]) // 树形结构

const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

interface DeptMemberVo {
  id: undefined;
  nickname: undefined;
  name: undefined;
  idcard: undefined;
  groupName: undefined;
  changeBalance: number;
  changeType: number;
  deptIds: number[];
  deptNames: string;
}

const formData = ref<DeptMemberVo>({
  id: undefined,
  nickname: undefined,
  name: undefined,
  idcard: undefined,
  groupName: undefined,
  changeBalance: 0,
  changeType: 1,
  deptIds: [],
  deptNames: ''
});
const formRules = reactive({
  // changeBalance: [{ required: true, message: '变动余额不能为空', trigger: 'blur' }],
});
const formRef = ref(); // 表单 Ref

/** 查找部门 */
const findDeptById = (id: number) => {
  for (const dept of depts.value) {
    if (dept.id === id) return dept;
  }
  return undefined;
};

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      const user = await UserApi.getUser(id);
      formData.value.id = user.id;
      formData.value.name = user.name;
      formData.value.idcard = user.idcard;
      formData.value.nickname = user.nickname;
      formData.value.groupName = user.groupName;
      formData.value.deptIds = user.deptIds;
      formData.value.deptNames = user.deptNames;
    } finally {
      formLoading.value = false;
    }
  }
  // 加载部门树
  depts.value = await DeptApi.getSimpleDeptList()
  deptList.value = handleTree(depts.value)
};
defineExpose({open}); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value.validate();
  if (!valid) return;

  // 提交请求
  formLoading.value = true;
  // 设置选中部门名称
  formData.value.deptNames = formData.value.deptIds
    .map(id => findDeptById(id)?.name || '')
    .filter(Boolean)
    .join(',');
  const userData = formData.value as unknown as UserApi.UserVO
  try {
    await UserApi.bindDeptMember(userData);
    message.success(t('common.updateSuccess'));
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    nickname: undefined,
    name: undefined,
    idcard: undefined,
    groupName: undefined,
    changeBalance: 0,  // 注意：数字类型需要保持默认值
    changeType: 1,     // 注意：数字类型需要保持默认值
    deptIds: [],       // 数组类型重置为空数组
    deptNames: ''      // 字符串类型重置为空字符串
  };
  formRef.value?.resetFields();
};

</script>
